package cn.may.utils;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 压缩工具类
 *
 * @author mayuanbao
 * @date 2019-06-13 21:41
 */
public class ZipUtil {
    public static String zip(File sourceFile, String fileName, ZipOutputStream zipOutputStream) throws IOException {
        if (!sourceFile.exists()) {
            return "文件不存在";
        }
        if (sourceFile.isDirectory()) {
            if (fileName.endsWith("/")) {
                zipOutputStream.putNextEntry(new ZipEntry(fileName));
            } else {
                zipOutputStream.putNextEntry(new ZipEntry(fileName + "/"));
            }
            zipOutputStream.closeEntry();
            File[] children = sourceFile.listFiles();
            if (children != null && children.length > 0) {
                for (File child : children) {
                    zip(child, fileName + "/" + child.getName(), zipOutputStream);
                }
                return "压缩完毕";
            } else {
                return "文件夹为空";
            }
        }
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(sourceFile))){
            zipOutputStream.putNextEntry(new ZipEntry(fileName));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = in.read(bytes)) != -1) {
                zipOutputStream.write(bytes, 0, len);
            }
            zipOutputStream.close();
            return "success";
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
